package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     * 二合一，用户登录也是有游客登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) throws JsonProcessingException {
        if (StringUtils.isNotBlank(dto.getPassword())&&StringUtils.isNotBlank(dto.getPhone())){
            //1.1根据手机号获取用户信息
            ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //1.2比对密码
            boolean result = BCrypt.checkpw(dto.getPassword(), apUser.getPassword());
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //1.3返回数据
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }
        Map<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(0L);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser> findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
